<template>
  <div>
    <main-box one="商品管理" two="添加商品">
      <!-- 提示框 -->
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!-- 步骤条 -->
      <!-- activeIndex-0是为了隐式转换 -->
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-position="top"
        label-width="80px"
      >
        <!-- Tab切换 -->
        <el-tabs tab-position="left" :before-leave="tabToggle" v-model="activeIndex" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0" >
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品重量">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品数量">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_cat" label="商品分类">
                <!-- 级联选择器 -->
                <el-cascader
                expand-trigger="hover"
                  v-model="addForm.goods_cat"
                  :options="catelist"
                  :props="catelistProps"
                  @change="handleChange"
                ></el-cascader>
              </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1" >
            <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
               <!-- 复选框组 -->
                <el-checkbox-group v-model="item.attr_vals" >
                <el-checkbox v-for="(cb,i) in item.attr_vals" :key="i" :label="cb" border></el-checkbox>
                </el-checkbox-group>
            </el-form-item>      
             </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
  action="http://127.0.0.1:8888/api/private/v1/upload"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :on-success="handSuccess"
  list-type="picture"
  :headers="headerObj">
  <el-button size="small" type="primary">点击上传</el-button>
</el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add" class="lastBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </main-box>

    <el-dialog
  title="图片预览"
  :visible.sync="previewDialogVisible"
  width="50%">
    <img :src="previewUrl" alt="" class="previewImg">
</el-dialog>

  </div>
</template>
<script>
import _ from 'lodash';
export default {
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_cat: [],
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_introduce: "",
        pics:[],
        attrs:[]
      },
      addFormRules: {
        goods_name: [{ required: true, message: "必填项", trigger: "blur" }],
        goods_cat: [{ required: true, message: "必填项", trigger: "blur" }],
        goods_weight: [{ required: true, message: "必填项", trigger: "blur" }],
        goods_number: [{ required: true, message: "必填项", trigger: "blur" }]
      },
      catelist: [],
      catelistProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children'
      },
      headerObj:{
        Authorization :window.sessionStorage.getItem('token')
      },
      manyTableData:[],
      onlyTableData:[],
      previewDialogVisible:false,
      previewUrl:'',
    };
  },
  mounted() {
    this.getcateList();
  },
  methods: {
    async getcateList() {
      const { data: res } = await this.$http.get("categories");
      // console.log(res);
      if (res.meta.status == 200) {
        this.catelist = res.data;
      }
    },
    handleChange(){
        if(this.addForm.goods_cat.length!=3){
             this.addForm.goods_cat=[]
        }
    },
    tabToggle(activeName,oldActiveName){
        // console.log(activeName,oldActiveName);
            if(oldActiveName=='0'&&this.addForm.goods_cat.length!=3){
                this.$message.error('请选择商品分类');
                 return false;
            }
    },
    async tabClicked(){
      // 这是动态参数列表
        if(this.activeIndex=='1'){
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{
            sel:'many'
        }});
        if(res.meta.status!=200){
          this.$message.error('获取动态参数失败')
        } 
        // console.log(res.data);
        res.data.forEach(item=>{
         item.attr_vals= item.attr_vals.length==0?[]:item.attr_vals.split(' ');
        })
        this.manyTableData=res.data;
        };
        if(this.activeIndex=='2'){
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{
                params:{sel:'only'}
            })
            if(res.meta.status!=200){
                return this.$message.error('获取静态属性失败')
            }
            this.onlyTableData=res.data;
        }
    },
    // 图片预览
    handlePreview(file){
      // console.log(file);
      this.previewUrl=file.response.data.url;this.previewDialogVisible=true;
    },
    handleRemove(file){
      // console.log(file);
      const filePath=file.response.data.tmp_path;
      const i= this.addForm.pics.findIndex(x=>{
        x.pic==filePath
      })
      this.addForm.pics.splice(i,1);
      console.log(this.addForm.pics);
    },
    //上传成功的回调
    handSuccess(response){
      console.log(response);
      if(response.meta.status!=200) {
        return this.$message.error('图片上传失败')
      }
      this.addForm.pics.push({
        "pic":response.data.tmp_path
      });
      // console.log(this.addForm.pics);
    },
  add(){
      // console.log(this.addForm);
      this.$refs.addFormRef.validate(async v=>{
        if(!v){
          return this.$message.error('请把表单填写完整');
        }
        // 深拷贝  下载lodash  cloneDeep(obj)
        const form=_.cloneDeep(this.addForm);
        form.goods_cat=form.goods_cat.join(',');
        this.manyTableData.forEach(item=>{
          const newInfo={
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          }
        this.addForm.attrs.push(newInfo);
      })
       this.onlyTableData.forEach(item=>{
          const newInfo={
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          }
        this.addForm.attrs.push(newInfo);
      })
      form.attrs=this.addForm.attrs;
      // console.log(form);
        const {data:res}=await this.$http.post('goods',form);
        console.log(res);
        if(res.meta.status==201) {
          this.$message.success('添加商品成功！');
          this.$router.push('/goods');
        }
      })
     }
   },
  computed:{
    //   cateId是商品分类ID
      cateId(){
          if(this.addForm.goods_cat.length==3){
              return this.addForm.goods_cat[2];
          } else{
              return null;
          }
      }
  }
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 25px 0;
}
.el-step__title {
  font-size: 12px;
}
.el-checkbox{
  margin:0 5px 0 0 !important ;
}
.previewImg{
  width: 100%;
}
.lastBtn{
  margin-top: 10px;
}
</style>